<template>
	<view>
		<!--  顶部组件  -->
		<topNavigation type="home" title="我的"></topNavigation>

		<!--  头像昵称 非微信  -->
		<view v-if="env != 'weixin'" class="info_out">
			<view class="info" @click="getuserinfo">
				<image class="info_head_image"
					:src="userInfo.avatarUrl ? userInfo.avatarUrl : '/static/image/page/mime/default_head.png'"></image>
				<view class="info_nick">{{userInfo.nickName ? userInfo.nickName : '读现代诗'}}</view>
			</view>
			<!--  授权登录  -->
			<button v-if="!userInfo.avatarUrl" class="auth_button" open-type="getUserInfo" @click="getuserinfo"
				style="width: 200rpx;margin: 0; margin-left: 40rpx;">授权登录</button>
		</view>

		<!--  头像昵称 微信  -->
		<view v-else class="info_out_wx">
			<view class="wx_button_out">
				<button class="info_wx" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
					<image class="info_head_image"
						:src="userInfo.avatarUrl ? userInfo.avatarUrl : '/static/image/page/mime/default_head.png'">
					</image>
				</button>
				<input type="nickname" class="info_nick_wx" placeholder="请输入昵称"
					placeholder-class="info_nick_wx_placeholder" v-model="userInfo.nickName" @blur="onNickName" />
			</view>
		</view>

		<!--  菜单  -->
		<view class="menu_out" v-for="(item, index) in menuList" :key="index" @click="goToMenuPage(item.url)">
			<!--  内容  -->
			<view class="menu_content">
				<!--  左边  -->
				<view class="menu_left">
					<image class="menu_icon_image" :src="item.icon"></image>
					<view>{{item.name}}</view>
				</view>
				<!--  右边  -->
				<view v-if="item.name == '消息提醒(评论)' && noticeCount > 0" class="menu_right_notice">
					{{noticeCount}}
				</view>
				<image v-else class="menu_right" src="/static/image/common/right.png">
				</image>
			</view>
			<!--  下划线  -->
			<view v-if="index != 4" class="menu_line"></view>

		</view>


		<!--  底部组件  -->
		<bottom-navigation :navigationIndex="3"></bottom-navigation>
	</view>
</template>

<script>
	import userUtil from '@/utils/user/userUtil.js'
	import toastUtil from '@/utils/toastUtil.js'
	import storageUtil from '@/utils/storageUtil.js'
	import {
		getProvider
	} from '@/utils/user/userConfig.js'

	// 获取应用实例
	const app = getApp()
	export default {
		data() {
			return {
				// 系统平台
				system: app.globalData.system,
				// 导航栏高度
				navigationHeight: app.globalData.navigationHeight,
				// 统一背景颜色
				unifyBgColor: app.globalData.unifyBgColor,
				// 顶部导航栏高度
				topNavigationHeight: app.globalData.topNavigationHeight,
				// 主色调
				mainColor: app.globalData.mainColor,
				// 分页提示
				pageMsg: '没有更多了',
				// 分页提示 ---- 加载中
				pageMsgLoading: '加载中',
				// 分页提示 ---- 没有更多了
				pageMsgNone: '没有更多了',
				// 用户信息
				userInfo: {
					nickName: "",
					avatarUrl: "",
					authorizeFlag: false
				},
				// 菜单集合
				menuList: [{
					name: '导出体重数据',
					url: "/pages/mime/exportWeight/exportWeight",
					icon: "/static/image/page/mime/export.png"
				}, {
					name: '配置',
						url: "/pages/mime/config/config",
						icon: "/static/image/page/mime/config.png"
					}, {
					name: '意见反馈',
					url: "/pages/mime/suggest/suggest",
					icon: "/static/image/page/mime/suggest.png"
				}, {
					name: '关于我们',
					url: "/pages/mime/about/about",
					icon: "/static/image/page/mime/about.png"
				// }, {
				// 	name: '广告(支持作者)',
				// 	url: "/pages/mime/ad/ad",
				// 	icon: "/static/image/page/mime/ad.png"
				}],
				// menuList: [{
				// 	name: '导出体重数据',
				// 	url: "/pages/mime/exportWeight/exportWeight",
				// 	icon: "/static/image/page/mime/export.png"
				// }, {
				// 	name: '意见反馈',
				// 	url: "/pages/mime/suggest/suggest",
				// 	icon: "/static/image/page/mime/suggest.png"
				// }, {
				// 	name: '关于我们',
				// 	url: "/pages/mime/about/about",
				// 	icon: "/static/image/page/mime/about.png"
				// }],
				timer1: null,
				timer2: null,
				timer3: null,
				timer4: null,
				// 环境变量
				env: null
			}
		},
		onLoad() {
			// 查询环境
			this.env = storageUtil.getEnv()
			getProvider().then((res) => {
				this.env = res
			}, (res) => {
				toastUtil.showToast(res.errMsg)
			})
			// 初始化用户
			userUtil.initUser(() => {
				// 查看用户
				this.userInfo = storageUtil.getUserInfo()
			});

		},
		methods: {
			getUserInfo_qq() {
				uni.getUserInfo({
					withCredentials: true,
					provider: storageUtil.getEnv(),
					success: (res) => {
						console.log(
							'uni.getUserInfo  success : res：', res);
						console.log('用户昵称为：', res.userInfo.nickName);
						console.log('storageUtil.getUserInfo() : ', storageUtil.getUserInfo())

						// 清除定时器
						clearTimeout(this.timer1);
						clearTimeout(this.timer2);
						clearTimeout(this.timer3);
						clearTimeout(this.timer4);

						let data = {
							nickName: res.userInfo.nickName,
							avatarUrl: res.userInfo.avatarUrl,
							_id: storageUtil.getUserInfo()._id
						}
						console.log('data : ', data)
						userUtil.updateUser(data)
							.then(() => {
								userUtil.getUser()
									.then(() => {
										this.userInfo = storageUtil.getUserInfo()
									})
								toastUtil.showToast('授权成功')
							}, () => {
								toastUtil.showToast('授权失败')
							})
					},
					fail: (res) => {
						console.log(
							'uni.getUserInfo  fail : res：',
							res);

					},
					complete: (res) => {
						console.log(
							'uni.getUserInfo  complete : res：', res);

					}
				})
			},
			// 定时调用
			getUserInfo_setTime_qq() {

				let timer1 = setTimeout(() => {
					this.getUserInfo_qq()
				}, 2000)
				let timer2 = setTimeout(() => {
					this.getUserInfo_qq()
				}, 4000)
				let timer3 = setTimeout(() => {
					this.getUserInfo_qq()
				}, 8000)
				let timer4 = setTimeout(() => {
					this.getUserInfo_qq()
				}, 12000)
				this.timer1 = timer1
				this.timer2 = timer2
				this.timer3 = timer3
				this.timer4 = timer4
			},
			// 获取用户信息
			getuserinfo(e) {
				console.log("getuserinfo.............")
				getProvider().then((env) => {
					if ('qq' == env) {
						uni.login({
							success: () => {
								this.getUserInfo_qq()
								this.getUserInfo_setTime_qq()
							},
						})


					} else if ('weixin' == env) {
						uni.getUserInfo({
							desc: '我们将收集您的信息用于诗歌创作、评论的展示',
							success: (res) => {
								console.log('res：', res);
								console.log('用户昵称为：', res.userInfo.nickName);
								console.log('storageUtil.getUserInfo() : ',
									storageUtil
									.getUserInfo())
								let data = {
									nickName: res.userInfo.nickName,
									avatarUrl: res.userInfo.avatarUrl,
									_id: storageUtil.getUserInfo()._id
								}
								console.log('data : ', data)
								userUtil.updateUser(data).then(() => {
									userUtil.getUser().then(() => {
										this.userInfo = storageUtil
											.getUserInfo()
									})
									toastUtil.showToast('授权成功')
								}, () => {
									toastUtil.showToast('授权失败')
								})
							},
							fail: (res) => {
								toastUtil.showToast('授权失败')
							},
							complete: (res) => {
								console.log('complete : res：', res);
							}
						})

					} else {
						uni.login({
							success: () => {
								uni.getUserInfo({
									withCredentials: true,
									provider: storageUtil.getEnv(),
									success: (res) => {
										console.log('res：', res);
										console.log('用户昵称为：', res.userInfo.nickName);
										console.log('storageUtil.getUserInfo() : ',
											storageUtil
											.getUserInfo())
										let data = {
											nickName: res.userInfo.nickName,
											avatarUrl: res.userInfo.avatarUrl,
											_id: storageUtil.getUserInfo()._id
										}
										console.log('data : ', data)
										userUtil.updateUser(data).then(() => {
											userUtil.getUser().then(() => {
												this.userInfo = storageUtil
													.getUserInfo()
											})
											toastUtil.showToast('授权成功')
										}, () => {
											toastUtil.showToast('授权失败')
										})
									},
									fail: (res) => {
										console.log('fail : res：', res);
										uni.showModal({
											title: '重新授权',
											content: '授权失败，若是想要重新授权需要打开设置页面，并需要您同意授权，是否打开设置页面?',
											success: function(res) {
												if (res.confirm) {
													console.log('用户点击确定');
													uni.openSetting({
														success(res) {
															console
																.log(
																	res
																	.authSetting
																)
														}
													});
												} else if (res.cancel) {
													console.log('用户点击取消');
												}
											}
										});
									},
									complete: (res) => {
										console.log('complete : res：', res);
									}
								})
							}
						})
					}
				})




			},

			// 跳转用户菜单
			goToMenuPage(url) {
				console.log(url)
				wx.navigateTo({
					url: url,
				})
			},

			onChooseAvatar(e) {
				console.log("onChooseAvatar...........")
				console.log(e)
				let value = e.detail.avatarUrl

				// 删除旧的头像
				this.deleteOldAvatar(storageUtil.getUserInfo().avatarUrl, value)
			},

			// 删除旧的头像
			deleteOldAvatar(oldUrl, newUrl) {
				//删除旧的头像
				uniCloud.callFunction({
						name: 'deleteOldFile',
						data: {
							fileId: oldUrl,
						}
					})
					.then((res) => {
						console.log('删除旧头像成功 : res ', res)
						console.log(res.fileId);
						this.uploadNewAvatar(newUrl)
					}, (res) => {
						console.log('删除旧头像失败 : res ', res)
						// toastUtil.showToast("删除旧头像失败，授权失败!")
						this.uploadNewAvatar(newUrl)
					})
			},

			// 上传新的头像
			uploadNewAvatar(newUrl) {
				//上传新的头像
				// promise方式
				uniCloud.uploadFile({
					filePath: newUrl,
					cloudPath: 'avatar_url_wx_' + storageUtil.getUserInfo().openId + '.jpg',
					onUploadProgress: function(progressEvent) {
						console.log(progressEvent);
						var percentCompleted = Math.round(
							(progressEvent.loaded * 100) / progressEvent.total
						);
					}
				}).then((res) => {
					console.log('上传头像成功 : res ', res)
					this.updateUserAvatarUrl(res.fileID)
				}, (res) => {
					console.log('上传头像失败 : res ', res)
					toastUtil.showToast("上传头像失败，授权失败!")
				})
			},
			// 更新头像
			updateUserAvatarUrl(finlyUrl) {
				let data = {
					avatarUrl: finlyUrl,
					_id: storageUtil.getUserInfo()._id
				}
				console.log('data : ', data)
				userUtil.updateUser(data).then(() => {
					userUtil.getUser().then(() => {
						this.userInfo = storageUtil.getUserInfo()
					})
					toastUtil.showToast('授权成功')
				}, () => {
					toastUtil.showToast('授权失败')
				})
			},
			onNickName(e) {
				console.log("onNickName...........")
				console.log(e)
				let value = e.detail.value
				let data = {
					nickName: value,
					_id: storageUtil.getUserInfo()._id
				}
				console.log('data : ', data)
				userUtil.updateUser(data).then(() => {
					userUtil.getUser().then(() => {
						this.userInfo = storageUtil
							.getUserInfo()
					})
					toastUtil.showToast('授权成功')
				}, () => {
					toastUtil.showToast('授权失败')
				})
			}
		}
	}

</script>

<style>
	/*  信息外部  */
	.info_out {
		display: flex;
		align-items: center;
		height: 250rpx;
		width: 100%;
		background-color: rgb(150, 150, 150);
		color: white;
	}

	/*  用户信息  */
	.info {
		padding-left: 50rpx;

	}

	/*  头像  */
	.info_head_image {
		width: 80rpx;
		height: 80rpx;
		border-radius: 100%;
	}

	/*  昵称  */
	.info_nick {
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 25rpx;
	}

	/*  授权按钮  */
	.auth_button {
		background-color: rgb(7, 193, 93);
		color: white;
		font-size: 25rpx;
		width: 200rpx;
		border: 0;
		padding: 10rpx;
	}

	/*  信息外部  微信 */
	.info_out_wx {
		display: flex;
		align-items: center;
		height: 250rpx;
		width: 100%;
		background-color: rgb(150, 150, 150);
		color: white;
	}

	/*  微信的按钮的外部  */
	.wx_button_out {
		padding-left: 30rpx;
	}

	/*  用户信息 微信  */
	.info_wx {
		width: 80rpx;
		height: 80rpx;
		padding: 0 !important;
		margin: 0 !important;
		border-radius: 80px;
		border: none;
		outline: none;
		background: rgba(0, 0, 0, 0);
	}

	.info_wx::after {
		border: none;
	}

	/*  昵称 微信  */
	.info_nick_wx {
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		font-size: 25rpx;
		color: white;
	}

	/*  没有输入框的值  */
	.info_nick_wx_placeholder {
		color: white;
	}

	/*  菜单  */

	/*  菜单外部  */
	.menu_out {
		height: 120rpx;
		padding-left: 20rpx;
		padding-right: 20rpx;
		background-color: rgb(209, 208, 180);
	}

	/*  下划线  */
	.menu_line {
		background-color: rgb(170, 170, 170);
		width: 100%;
		height: 2rpx;
	}

	/*  菜单外部  */
	.menu_content {
		display: flex;
		justify-content: space-between;
		align-items: center;
		height: 118rpx;
		background-color: rgb(209, 208, 180);
	}

	/*  菜单左边  */
	.menu_left {
		display: flex;
		align-items: center;
		height: 100%;
	}

	/*  图标  */
	.menu_icon_image {
		padding-right: 15rpx;
		width: 40rpx;
		height: 40rpx;
	}

	/*  右边图标  */
	.menu_right {
		width: 40rpx;
		height: 40rpx;
	}

	/*  消息提醒  */
	.menu_right_notice {
		width: 70rpx;
		height: 70rpx;
		border-radius: 50%;
		background-color: red;
		color: white;
		text-align: center;
		line-height: 70rpx;
	}
</style>
